<template>
  <div class='order-list-page'>
    <div class="order-title">
      <div :class="['title-item', orderState===-1?'choose-item':'']" @click="chooseState(-1)">全部订单</div>
      <div :class="['title-item', orderState===10?'choose-item':'']" @click="chooseState(10)">待付款</div>
      <div :class="['title-item', orderState===20?'choose-item':'']" @click="chooseState(20)">待发货</div>
      <div :class="['title-item', orderState===30?'choose-item':'']" @click="chooseState(30)">待收货</div>
      <div :class="['title-item', orderState===40?'choose-item':'']" @click="chooseState(40)">已完成</div>
      <div :class="['title-item', orderState===5?'choose-item':'']" @click="chooseState(5)">售后</div>
      <div :class="['title-item', orderState===0?'choose-item':'']" @click="chooseState(0)">已取消</div>
    </div>
    <div class="order-info" v-for="(item,index) in orderList" :key="index">
      <div @click="gotoOrderDetail(item)">
        <div class="merchant-info">
          <div class="order-state">
            <span>{{item.orderId}}</span>
            <span style="margin-left: 0.21rem">></span>
            <span style="color: #fd7418; margin-left: 0.21rem">{{item.orderStatus === 10?'待付款':item.orderStatus === 20?'待发货':item.orderStatus=== 30?'待收货':item.orderStatus === 0?'已取消':item.orderStatus=== '5'?'退款成功':'退货成功'}}</span>
          </div>
        </div>
        <div class="goods-info" v-for="(item,index) in item.productList" :key="index">
          <img class="goods-item-image" :src="item.picUrl">
          <div class="goods-item-info">
            <div class="goods-name">{{item.productName}}</div>
            <!--<div class="goods-norms">{{item.goodsNorms}}</div>-->
            <div class="goods-norms" v-if="item.propertiesName !== null && item.propertiesName.length !== 0 && item.propertiesName !== ''">{{item.propertiesName}}</div>
            <div style="height: 1.17rem" v-if="!(item.propertiesName !== null && item.propertiesName.length !== 0 && item.propertiesName !== '')"></div>
            <div class="goods-info-bottom">
              <div class="goods-info-left">
                <div class="goods-real-fee">
                  <div class="icon">￥</div>
                  {{item.actualPrice}}
                </div>
              </div>
              <div class="goods-info-right">
                x{{item.buyProductNumber}}
              </div>
            </div>
          </div>
        </div>
        <div class="order-item-bottom">
          <div class="order-item-bottom-left">
            <span>总计：</span>
            <span style="color: #fd7418;">￥{{item.orderPrice}}</span>
          </div>
          <div class="order-item-bottom-right">
            <span v-if="item.orderStatus === 10" class="color-gray" @click="closeOrder(item)">取消订单</span>
            <!--<span v-if="item.orderStatus === 40" class="color-gray">退换/售后</span>-->
            <!--<span v-if="item.orderStatus === 20 || item.orderStatus === 40" class="color-gray">查询进度</span>-->
            <!--<span v-if="item.orderStatus === 30" class="color-gray">查询物流</span>-->
            <span v-if="item.orderStatus === 0" class="color-gray" @click="deleteOrder(item)">删除订单</span>
            <!--<span v-if="item.orderStatus === 20" class="color-orange">申请退款</span>-->
            <span v-if="item.orderStatus === 10" class="color-orange" @click="goPay(item)">去支付</span>
            <span v-if="item.orderStatus === 30" class="color-orange" @click="sureOrder(item)">确认收货</span>
          </div>
        </div>
      </div>
    </div>

    <el-dialog
      title="提示"
      :visible.sync="modalStatus">
      <div class="qian-dialog" slot="content">
        <div class="dialog-content">
          <div class="dialog-top">
            <img class="header-img" src="../../assets/dialog-bg.png" mode="scaleToFill">
          </div>
          <div class="dialog-main">
            <div class="dialog-title">
              确认要取消该笔订单吗？
            </div>
            <div class="handle-btns">
              <div class="submit-btn">确定</div>
              <div class="cancel-btn">取消</div>
            </div>
          </div>
        </div>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { API } from '../../config'
export default{
  data(){
    return {
      orderState: -1,  // -1 全部订单 10 待支付  20 待发货  30 待收货  0 已取消
      orderList: [],
      modalStatus: false,
      pageNum: 1
    }
  },
  methods:{
    chooseState (num) {
      if (this.orderState !== num) {
        this.orderState = num
        this.initFun()
      }
    },
    gotoOrderDetail (item) {
      this.$router.push({
        path: '/order/orderDetail?id=' + item.orderId
      })
    },
    //确认收货
    sureOrder (item){
      this.$axios.post( API + 'order/confirm-receipt?orderId=' + item.orderId).then((resp)=>{
        let obj = resp.data
        if (obj.code === 200) {
          this.$message('确认成功')
          this.$router.push({
            path: '/user'
          })
        }
      })
      event.stopPropagation ? event.stopPropagation(): event.cancelBubble = true; // 阻止冒泡
    },
    goPay(item) {
      let vm = this
      const orderId = item.orderId
      this.shareAlbum(orderId)
      event.stopPropagation ? event.stopPropagation(): event.cancelBubble = true; // 阻止冒泡
      // this.$axios.post( API + '/order/gopay?orderId=' + this.addressId).then((resp)=>{
      //   let obj = resp.data
      //   if (obj.code === 200) {
      //     this.shareAlbum(res.data.data.orderId)
      //     // let [err, result] = await pay(obj.data)
      //     // console.log(err)
      //     // if (result) {
      //     //   // 成功
      //     //   this.$message('支付成功')
      //     //   return wx.redirectTo({
      //     //     url: '/pages/shopping/paySuccess2?orderId=' + orderId
      //     //   })
      //     // }
      //   }
      //   // todo 弹框
      //   // this.$message('申请支付失败')
      //   this.$router.push({
      //     path: '/order/orderDetail?id=' + orderId
      //   })
      // })
      // const obj = await this.S.shopping.gopay({orderId: orderId})
      
    },
    closeOrder (item) {
      let accesstoken = this.getLocalStorage('accesstoken')
      this.$axios.post( API + '/order/cancel?orderId='+item.orderId,{},{
          headers: {'accesstoken': accesstoken}//设置header信息
        }).then((resp)=>{
        let res = resp.data
        if (res.code === 200) {
          this.$message('取消成功')
          this.initFun()
        } else {
          this.$message('取消失败')
        }
      })
      event.stopPropagation ? event.stopPropagation(): event.cancelBubble = true; // 阻止冒泡
    },
    deleteOrder (item) {
      let accesstoken = this.getLocalStorage('accesstoken')
      this.$axios.post( API + '/order/delete?orderId=' + item.orderId,{},{
          headers: {'accesstoken': accesstoken}//设置header信息
        }).then((resp)=>{
        let res = resp.data
        if (res.code === 200) {
          this.$message('删除成功')
          this.initFun()
        } else {
          this.$message('删除失败')
        }
      })
      event.stopPropagation ? event.stopPropagation(): event.cancelBubble = true; // 阻止冒泡
    },
    getList (pageNum) {
      var orderType = null
      let accesstoken = this.getLocalStorage('accesstoken')
      if (parseInt(this.orderState) !== -1) {
        orderType = parseInt(this.orderState)
      }
      this.orderState = parseInt(this.orderState)
      var params = {
        'orderType': orderType,
        'pageNum': pageNum || 1,
        'pageSize': 10,
        'salesStatus': null
      }
      this.$axios.post( API + '/order/getlist',params,{
          headers: {'accesstoken': accesstoken}//设置header信息
        }).then((resp)=>{
        let res = resp.data
        this.orderList = params.pageNum === 1 ? [] : this.orderList
        if (res.code === 200) {
          if (res.data.data.length > 0) {
            res.data.data.forEach(item => {
              item.orderPrice = item.orderPrice/100
              item.productList.forEach(s => {
                s.actualPrice = s.actualPrice/100
              })
            })
          }
          this.orderList = [...this.orderList, ...res.data.data]
        }
      })
    },
    // 支付
    shareAlbum(orderId) {
        let params = {};
        let url = 'wechatPay：//orderId=' + orderId;//URL Scheme 安卓小伙伴提供
        this.shareJump(url, params);
    },
    // 分享跳转
    shareJump(url, param) {
        // 判断是否是微信
        var is_weixin = (function () { return navigator.userAgent.toLowerCase().indexOf('micromessenger') !== -1 })();
        if (is_weixin) {
            // 微信则跳转下载页
            window.location.href = "https://www.pgyer.com/Q8AS?sig=Myi3vdBmKRpads5BP6VZd%2FHbxfG%2Bfm6mcEwZZM3SK3Y5o%2FS7QZ%2B%2BI6SJ3%2BdQNAmT"
            return;
        }
        // 非微信拼接参数
        let params = param
        let urls = url;
        let first = true;
        if (params) {
            for (let i in params) {
                if (first) {
                    urls += "?"
                    first = false;
                } else {
                    urls += "&"
                }
                urls += i + "=" + params[i]
            }
            //console.log("getUrlend", urls);
        }
        // 安卓端跳转
        var iFrame;
        var u = navigator.userAgent;
        var isAndroid = u.indexOf('Android') > -1 || u.indexOf('Adr') > -1; //android终端
        var isiOS = !!u.match(/\(i[^;]+;( U;)? CPU.+Mac OS X/); //ios终端
        // console.log("isAndroid", isAndroid, isiOS);
        if (isAndroid) {
            //安卓终端使用iframe
            iFrame = document.createElement("iframe");
            iFrame.setAttribute("src", urls);
            iFrame.setAttribute("style", "display:none;");
            iFrame.setAttribute("height", "0px");
            iFrame.setAttribute("width", "0px");
            iFrame.setAttribute("frameborder", "0");
            document.body.appendChild(iFrame);
            // 发起请求后这个 iFrame 就没用了，所以把它从 dom 上移除掉
            iFrame.parentNode.removeChild(iFrame);
            iFrame = null;
            // 如果用户没有安装APP，则提示用户去安装APP
            setTimeout(() => {
                window.location.href = "https://www.pgyer.com/Q8AS?sig=Myi3vdBmKRpads5BP6VZd%2FHbxfG%2Bfm6mcEwZZM3SK3Y5o%2FS7QZ%2B%2BI6SJ3%2BdQNAmT"; // 这里可以自行写一个延时关闭的弹窗，也可以跳转至app下载地址
            }, 2000);
        } else if (isiOS) {
            //iOS终端直接页面跳转
            window.location.href = urls;
            // 如果用户没有安装APP，则提示用户去安装APP
            setTimeout(() => {
                window.location.href = "https://www.pgyer.com/Q8AS?sig=Myi3vdBmKRpads5BP6VZd%2FHbxfG%2Bfm6mcEwZZM3SK3Y5o%2FS7QZ%2B%2BI6SJ3%2BdQNAmT"; // 这里可以自行写一个延时关闭的弹窗，也可以跳转至app下载地址
            }, 2000);
        } else {
            window.location.href = urls;
        }
      // window.location.href = urls;
    },
    initFun() {
      this.getList()
    }
  },
  mounted() {
      let options = this.$route.query
      this.orderState = options.state
      this.initFun()
    }
}
</script>

<style lang='less' scoped>
@import '../../css/order/orderList.less';
</style>
